package com.yanqu.road.logic.manager;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.*;

/**
 * @Author wpj
 * @Date 2020/9/27
 */
@Component
public class ServerListMgr implements ApplicationRunner {
    private static Set<Integer> serverIdList = new HashSet<>();
    private static ServerListMgr serverListMgr;
    @PostConstruct
    public void init() {
        serverListMgr = this;
    }
    @Autowired
    private  JdbcTemplate jdbcTemplate;
    /**
     * 检查缓存内serverId与ck内服务器id的差异
     */
    public static void checkServerIdList() {
        Set<String> tableNameList= queryTableName();
        Map<Integer,Integer> tableNameCkMap=new HashMap<>();
        for(String name:tableNameList){
            if(name.contains("item_change_detail_")){
                Integer serverId= Integer.valueOf(name.substring(name.lastIndexOf("_")+1, name.length()));
                tableNameCkMap.put(serverId,serverId);
            }
        }
        Set<Integer> serverIdNewList = new HashSet<>();
        for(Integer serverId:serverIdList){
            if(!tableNameCkMap.containsKey(serverId)){
                creatTableName(serverId);
                serverIdNewList.add(serverId);
            }
        }
        if(CollectionUtils.isNotEmpty(serverIdNewList)){
            serverIdList.addAll(serverIdNewList);
        }

    }
    /**
    * 创建新表
    * */
    private static void creatTableName(Integer serverId) {
        serverListMgr.jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS item_change_detail_"+serverId+" (\n" +
                "  `app_id` UInt32 COMMENT '统计中心分布的id',\n" +
                "  `device_id` String COMMENT '设备id',\n" +
                "  `source_id` String COMMENT '来源id',\n" +
                "  `source_name` Nullable(String) COMMENT '来源名称',\n" +
                "  `user_id` String COMMENT '用户id，即open_id',\n" +
                "  `user_name` Nullable(String) COMMENT '用户名称',\n" +
                "  `server_id` String COMMENT '服务器id',\n" +
                "  `server_name` Nullable(String) COMMENT '服务器名称',\n" +
                "  `role_id` String COMMENT '角色id',\n" +
                "  `role_name` String COMMENT '角色名称',\n" +
                "  `type` UInt8 COMMENT '类型 1消费 2产出',\n" +
                "  `type_item` UInt8 COMMENT '消费道具类型 1.资源类型(如元宝) 2道具类型(背包中的)',\n" +
                "  `type_item_id` String COMMENT '消费/产出点id',\n" +
                "  `type_item_name` String COMMENT '消费/产出点名称',\n" +
                "  `item_big_id` String COMMENT '资源和道具大类id',\n" +
                "  `item_id` String COMMENT '资源和道具小类id',\n" +
                "  `item_name` String COMMENT '资源和道具名称',\n" +
                "  `item_num` Float32 COMMENT '消费/产出数量',\n" +
                "  `created_time` UInt32 COMMENT '创建时间戳',\n" +
                "  `created_date` Date materialized toDate(created_time) COMMENT '创建时间，该引擎必选类型0000-00-00'\n" +
                ")\n" +
                "ENGINE=MergeTree()\n" +
                "PARTITION BY toYYYYMM(created_date)\n" +
                "ORDER BY (created_date)");
    }

    public static Set<Integer> getServerIdSet() {
        return serverIdList;
    }

    public synchronized static boolean hasServerId(String serverIdStr) {
        try {
            int serverId = Integer.valueOf(serverIdStr);
            if (serverIdList.contains(serverId)) {
                return true;
            }
            serverIdList.add(serverId);
            creatTableName(serverId);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            return false;
        }
    }

    /**
     * 读取clickhouse表 解析已有服务器id放进serverIdList
     *
     * */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 读取clickhouse表 解析已有服务器id放进serverIdList
        Set<String> tableNameList= queryTableName();
        for(String name:tableNameList){
            if(name.contains("item_change_detail_")){
                String number=name.substring(name.lastIndexOf("_")+1, name.length());
                serverIdList.add(Integer.valueOf(number));
            }
        }
    }

    private static Set<String> queryTableName() {
        Set<String> ServerTableName=new HashSet<>();
        SqlRowSet sqlRowSet= serverListMgr.jdbcTemplate.queryForRowSet("show tables like 'item_change_detail_%';");
        while (sqlRowSet.next()) {
            ServerTableName.add(sqlRowSet.getString("name"));
        }
        return ServerTableName;
    }
}
